﻿using EquipmentAlarmSystem.Models;
using EquipmentAlarmSystem.Service.ContentPushUnit;
using EquipmentAlarmSystem.Service.Models;
using EquipmentAlarmSystem.Service.Models.Enum;
using System.Collections;
using System.IO.Compression;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace EquipmentAlarmSystem.Service.Library;

/// <summary>
/// 基础库
/// </summary>
public static class Basics
{
    public static string BasicsPath = AppDomain.CurrentDomain.BaseDirectory;

    /// <summary>
    /// 配置获取
    /// </summary>
    public static Configure Config;

    /// <summary>
    /// 获取配置文件
    /// </summary>
    public static void GetConfig()
    {
        if (File.Exists(Path.Combine(BasicsPath, "json", "configfile.json")))
        {
            try
            {
                Config = JsonSerializer.Deserialize<Configure>(File.ReadAllText(Path.Combine(BasicsPath, "json", "configfile.json")));
            }
            catch (Exception)
            {

            }
        }
        else
        {
            Config = new()
            {
                SamplingInterval = 3,
                PushInterval = 600,
                EnablePush = false,
                Autograph = "【某某】",
                Heartbeat = "HEARTBEAT",
                EnableAlarmPush = false,
                EnableAlarmPushTime = 8,
                DisableAlarmPushTime = 18,
                LastSaveTime = DateTime.Now
            };
        }
    }

    /// <summary>
    /// 写入配置
    /// </summary>
    /// <returns></returns>
    public static string WriteConfig()
    {
        try
        {
            Config.LastSaveTime = DateTime.Now;


            PathCheck("json");

            File.WriteAllText(Path.Combine(BasicsPath, "json", "configfile.json"), JsonSerializer.Serialize(Config, new JsonSerializerOptions()
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            }));

            //获取全局配置
            GetConfig();

            return "保存成功";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    /// <summary>
    /// 时间统一格式化
    /// </summary>
    public static string GetDate
    {
        get
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        }
    }

    /// <summary>
    /// 路径检查
    /// </summary>
    /// <param name="path"></param>
    public static void PathCheck(string path)
    {
        if (path.Contains('/'))
        {
            var name = path.Split('/');

            string pathtemp = BasicsPath;

            foreach (var item in name)
            {
                pathtemp += Path.Combine(pathtemp, item);

                // 检查文件夹是否存在  
                if (!Directory.Exists(pathtemp))
                {
                    // 如果不存在，则创建文件夹  
                    Directory.CreateDirectory(pathtemp);
                }
            }
        }
        else
        {
            // 检查文件夹是否存在  
            if (!Directory.Exists(Path.Combine(BasicsPath, path)))
            {
                // 如果不存在，则创建文件夹  
                Directory.CreateDirectory(Path.Combine(BasicsPath, path));
            }
        }
    }

    /// <summary>
    /// HttpPost
    /// </summary>
    /// <param name="url"></param>
    /// <param name="json"></param>
    /// <returns></returns>
    public static async Task<string> HttpPostAsync(string url, object content)
    {
        using (var client = new HttpClient())
        {
            // 发送POST请求  
            HttpResponseMessage response = await client.PostAsJsonAsync(url, content);

            // 确保HTTP成功状态值  
            response.EnsureSuccessStatusCode();

            // 读取响应内容  
            string responseBody = await response.Content.ReadAsStringAsync();

            await Console.Out.WriteLineAsync(responseBody);

            return responseBody;
        }
    }

    /// <summary>
    /// HttpGet
    /// </summary>
    /// <returns></returns>
    public static string HttpGet(string url)
    {
        try
        {
            var client = new HttpClient();
            var response = client.GetAsync(new Uri(url)).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
        catch (Exception)
        {
            return "";
        }
    }

    /// <summary>
    /// 获取Uid
    /// </summary>
    /// <returns></returns>
    public static string GetUid()
    {
        return Guid.NewGuid().ToString();
    }

    /// <summary>
    /// 打包配置文件
    /// </summary>
    public static void PackagingConfigurationFiles(string path, string fileName)
    {
        if (File.Exists(fileName))
        {
            File.Delete(fileName);
        }
        ZipFile.CreateFromDirectory(path, fileName);
    }

    /// <summary>
    /// 部署配置文件
    /// </summary>
    public static void DeployConfigurationFiles(string file)
    {
        ZipFile.ExtractToDirectory(file, AppDomain.CurrentDomain.BaseDirectory, true);
    }

    /// <summary>
    /// 获取设备配置
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public static string GetEquipmentConfiguration(string id)
    {
        if (File.Exists(Path.Combine(BasicsPath, "json", $"{id}.json")))
        {
            try
            {
                return File.ReadAllText(Path.Combine(BasicsPath, "json", $"{id}.json"));
            }
            catch (Exception)
            {
                return "配置文件不存在";
            }
        }
        return "配置文件不存在";
    }

    /// <summary>
    /// 修改设备配置
    /// </summary>
    /// <returns></returns>
    public static string ModifEquipmentConfiguration(DeviceInformationSiemensS7 content)
    {
        try
        {
            PathCheck("json");

            if (Config.ServiceType == ServerType.Slave)
            {
                _ = HttpPostAsync($"{Config.ServiceAddress}/Equipment/ModifyEquipmentSiemensS7", content);
            }

            // 检查文件夹是否存在  
            if (!Directory.Exists("json"))
            {
                // 如果不存在，则创建文件夹  
                Directory.CreateDirectory("json");
            }

            string jsonString = JsonSerializer.Serialize(content, new JsonSerializerOptions()
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });

            File.Delete(Path.Combine(BasicsPath, "json", $"{content.Id}.json"));

            File.WriteAllText(Path.Combine(BasicsPath, "json", $"{content.Id}.json"), jsonString);

            PackagingConfigurationFiles("json", "config.zip");

            return $"{content.Name} 配置保存成功";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    /// <summary>
    /// 修改设备配置
    /// </summary>
    /// <returns></returns>
    public static string ModifEquipmentConfiguration(DeviceInformationModusTcp content)
    {
        try
        {
            PathCheck("json");

            if (Config.ServiceType == ServerType.Slave)
            {
                _ = HttpPostAsync($"{Config.ServiceAddress}/Equipment/ModifyEquipmentModusTcp", content);
            }

            // 检查文件夹是否存在  
            if (!Directory.Exists("json"))
            {
                // 如果不存在，则创建文件夹  
                Directory.CreateDirectory("json");
            }

            string jsonString = JsonSerializer.Serialize(content, new JsonSerializerOptions()
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });

            File.Delete(Path.Combine(BasicsPath, "json", $"{content.Id}.json"));

            File.WriteAllText(Path.Combine(BasicsPath, "json", $"{content.Id}.json"), jsonString);

            PackagingConfigurationFiles("json", "config.zip");

            return $"{content.Name} 配置保存成功";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    /// <summary>
    /// 数据分页
    /// </summary>
    /// <param name="list"></param>
    /// <param name="pageSize"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static List<List<T>> PaginateList<T>(List<T> list, int pageSize)
    {
        return list
            .Select((item, index) => new { item, index })
            .GroupBy(x => x.index / pageSize)
            .Select(x => x.Select(v => v.item).ToList())
            .ToList();
    }

    private static Verification verification;
    /// <summary>
    /// 验证码
    /// </summary>
    /// <returns></returns>
    public static string VerificationCode()
    {
        string filePath = Path.Combine(BasicsPath, "json", "verification.json");

        if (File.Exists(filePath))
        {
            try
            {
                verification = JsonSerializer.Deserialize<Verification>(File.ReadAllText(filePath))!;

                if (verification.Time < DateTime.Now)
                {
                    verification = null;
                }
            }
            catch (Exception)
            {
                verification = null;
            }
        }

        if (verification is null)
        {
            return "";
        }

        return verification.Code;
    }

    /// <summary>
    /// 生成验证码
    /// </summary>
    /// <param name="randomSixDigitNumber"></param>
    public static string SendCode()
    {
        VerificationCode();

        if (verification is not null)
        {
            return "验证码过期后，才能获取新验证码，验证码每次有效期24小时。\n仅支持工程师级获取！";
        }

        string filePath = Path.Combine(BasicsPath, "json", "verification.json");

        // 创建一个Random实例  
        Random random = new Random();

        // 生成一个随机的6位数字  
        int randomSixDigitNumber = random.Next(100000, 1000000); // 包含100000和999999 

        verification = new Verification();

        verification!.Code = randomSixDigitNumber.ToString();

        verification.Time = DateTime.Now.AddHours(24);

        string jsonString = JsonSerializer.Serialize(verification, new JsonSerializerOptions()
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        });

        File.WriteAllText(filePath, jsonString);

        if (Config.Contacts is not null)
        {
            foreach (var item in Config.Contacts)
            {
                if (item.Level == UserLevel.Engineer)
                {
                    //发送验证码
                    SmsAlarmConnection.SendSms(item.PhoneNumber, $"验证码：{verification.Code}，有效时间24小时！");
                }
            }
        }

        return verification.Code;
    }

    /// <summary>
    /// 获取设备ID
    /// </summary>
    /// <returns></returns>
    public static ArrayList GetID()
    {
        try
        {
            ArrayList arrayList = new();

            string path = Path.Combine(BasicsPath, "json");

            string[] txtFiles = Directory.GetFiles(path, "*.json");

            foreach (var item in txtFiles)
            {
                if (int.TryParse(Path.GetFileName(item).Replace(".json", ""), out _))
                {
                    arrayList.Add(Path.GetFileName(item).Replace(".json", ""));
                }
            }
            if (arrayList.Count <= 0)
            {
                return null;
            }
            return arrayList;
        }
        catch (Exception)
        {
            return null;
        }
    }

    /// <summary>
    /// 获取首页数据
    /// </summary>
    /// <returns></returns>
    public static string GetHomeData()
    {
        //加载数据
        ArrayList arrayList = GetID();

        List<DeviceInformation> strings = new();
        if (arrayList is null)
        {
            return "数据错误，无有效配置文件";
        }
        foreach (var item in arrayList)
        {
            DeviceInformation strings1 = new();

            string conf = File.ReadAllText(Path.Combine(BasicsPath, "json", $"{item}.json"));
            //配置文件序列化
            DeviceInformation deviceInformation = JsonSerializer.Deserialize<DeviceInformation>(conf);
            strings1.Id = deviceInformation.Id;
            strings1.Name = deviceInformation.Name;
            strings1.Describe = deviceInformation.Describe;
            strings1.Protocol = deviceInformation.Protocol;
            strings.Add(strings1);
        }
        return $"{JsonSerializer.Serialize(strings, new JsonSerializerOptions()
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        })}";
    }

    /// <summary>
    /// 添加设备
    /// </summary>
    /// <returns></returns>
    public static string AddEquipment(DeviceInformation device)
    {
        try
        {
            PathCheck("json");

            if (Config.ServiceType == ServerType.Slave)
            {
                _ = HttpPostAsync($"{Config.ServiceAddress}/Equipment/AddEquipment", device);
            }

            // 检查文件夹是否存在  
            if (!Directory.Exists("json"))
            {
                // 如果不存在，则创建文件夹  
                Directory.CreateDirectory("json");
            }

            string jsonString = JsonSerializer.Serialize(device, new JsonSerializerOptions()
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });

            File.Delete(Path.Combine(BasicsPath, "json", $"{device.Id}.json"));

            File.WriteAllText(Path.Combine(BasicsPath, "json", $"{device.Id}.json"), jsonString);

            PackagingConfigurationFiles("json", "config.zip");

            return $"{device.Name} 配置保存成功";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    /// <summary>
    /// 设备分组数据
    /// </summary>
    /// <returns></returns>
    public static PermissionManagementModel GroupingData()
    {
        //加载数据
        if (File.Exists(Path.Combine(BasicsPath, "json", "groupingData.json")))
        {
            try
            {
                string equipmentData = GetHomeData();

                List<DeviceInformation> homeData = JsonSerializer.Deserialize<List<DeviceInformation>>(equipmentData);

                var pmm = JsonSerializer.Deserialize<PermissionManagementModel>(File.ReadAllText(Path.Combine(BasicsPath, "json", "groupingData.json")));

                List<string> equipmentList = new();

                foreach (var item in pmm.EquipmentGroup)
                {
                    equipmentList.Add(item.Id);
                }
                foreach (var item in homeData)
                {
                    if (equipmentList.Contains(item.Id) == false)
                    {
                        pmm.EquipmentGroup.Add(new()
                        {
                            Id = item.Id,
                            Name = item.Name
                        });
                    }
                }
                return pmm;
            }
            catch (Exception)
            {
                return new();
            }
        }
        else
        {
            string equipmentData = Basics.GetHomeData();

            List<DeviceInformation> homeData = JsonSerializer.Deserialize<List<DeviceInformation>>(equipmentData);

            PermissionManagementModel managementModel = new();

            managementModel.Grouping = new() { "默认" };

            managementModel.EquipmentGroup = new();

            foreach (var item in homeData)
            {
                managementModel.EquipmentGroup.Add(new()
                {
                    Id = item.Id,
                    Name = item.Name
                });
            }
            return managementModel;
        }
    }

    /// <summary>
    /// 设备分组数据写入
    /// </summary>
    /// <returns></returns>
    public static string GroupingDataWrite(Groupings groupings)
    {
        //加载数据
        PermissionManagementModel val = GroupingData();

        List<string> Name = new();

        foreach (var item in val.EquipmentGroup)
        {
            if (item.Id == groupings.Id)
            {
                item.Grouping = groupings.Grouping;
            }
            Name.Add(item.Name);
        }

        //新建联系人
        if (Name.Contains(groupings.Name) == false)
        {
            val.EquipmentGroup.Add(groupings);
        }

        try
        {
            PathCheck("json");

            File.WriteAllText(Path.Combine(BasicsPath, "json", "groupingData.json"), JsonSerializer.Serialize(val, new JsonSerializerOptions()
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            }));

            GroupAuthorizationData(val);

            return "保存成功";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    /// <summary>
    /// 设备分组数据写入
    /// </summary>
    /// <returns></returns>
    public static string GroupingDataWrite(string name)
    {
        //加载数据
        var val = GroupingData();

        val.Grouping.Add(name);

        try
        {
            PathCheck("json");

            File.WriteAllText(Path.Combine(BasicsPath, "json", "groupingData.json"), JsonSerializer.Serialize(val, new JsonSerializerOptions()
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            }));

            return "保存成功";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    /// <summary>
    /// 获取授权分组数据
    /// </summary>
    /// <returns></returns>
    public static string GetGrouping(string id)
    {
        Hashtable AuthorizationConfiguration = new();

        if (id.Length <= 2)
        {
            return $"客户端序列号错误";
        }
        string configFile = Path.Combine(BasicsPath, "json", "authorizationDocuments.json");
        // 查找配置文件
        if (File.Exists(configFile))
        {
            string str = File.ReadAllText(configFile);
            AuthorizationConfiguration = JsonSerializer.Deserialize<Hashtable>(str);
            if (AuthorizationConfiguration.ContainsKey(id))
            {
                return AuthorizationConfiguration[id].ToString();
            }
            else
            {
                //记录客户端 方便授权
                AuthorizationConfiguration.Add(id, new List<string> { "默认" });
                File.WriteAllText(configFile, JsonSerializer.Serialize(AuthorizationConfiguration, new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                }));
                return $"客户端未获得授权,设备Id已记录";
            }
        }
        else
        {
            //记录客户端 方便授权
            AuthorizationConfiguration.Add(id, new List<string> { "默认" });
            File.WriteAllText(configFile, JsonSerializer.Serialize(AuthorizationConfiguration, new JsonSerializerOptions()
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            }));
            return $"客户端未获得授权,设备Id已记录";
        }
    }

    /// <summary>
    /// 获取分组数据
    /// </summary>
    /// <returns></returns>
    public static string ObtainGroupData(string id, string grouping)
    {
        if (GetGrouping(id).Contains("客户端"))
        {
            return "客户端授权错误";
        };
        //加载数据
        string file = Path.Combine(BasicsPath, "json", "groupAuthorizationData.json");

        var groupingData = JsonSerializer.Deserialize<Hashtable>(File.ReadAllText(file));

        var idList = JsonSerializer.Deserialize<List<string>>(groupingData[grouping].ToString());
        List<DeviceInformation> strings = new();

        foreach (var item in idList)
        {
            DeviceInformation strings1 = new();

            string conf = File.ReadAllText(Path.Combine(BasicsPath, "json", $"{item}.json"));
            //配置文件序列化
            DeviceInformation deviceInformation = JsonSerializer.Deserialize<DeviceInformation>(conf);
            strings1.Id = deviceInformation.Id;
            strings1.Name = deviceInformation.Name;
            strings1.Describe = deviceInformation.Describe;
            strings1.Protocol = deviceInformation.Protocol;
            strings.Add(strings1);
        }

        return $"{JsonSerializer.Serialize(strings, new JsonSerializerOptions()
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        })}";
    }

    /// <summary>
    /// 分组授权数据
    /// </summary>
    /// <returns></returns>
    public static void GroupAuthorizationData(PermissionManagementModel permission)
    {
        string file = Path.Combine(BasicsPath, "json", "groupAuthorizationData.json");

        Hashtable hashtable = new();

        List<string> groupingData = permission.Grouping;

        foreach (var item in groupingData)
        {
            List<string> stringsId = new();

            foreach (var itemS in permission.EquipmentGroup)
            {
                if (item == itemS.Grouping)
                {
                    stringsId.Add(itemS.Id);
                }
            }
            hashtable.Add(item, stringsId);
        }
        try
        {
            PathCheck("json");

            File.WriteAllText(file, JsonSerializer.Serialize(hashtable, new JsonSerializerOptions()
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            }));
        }
        catch (Exception)
        {

        }

    }

    /// <summary>
    /// 获取所有客户端id
    /// </summary>
    /// <returns></returns>
    public static List<string> GetAllClientIds()
    {
        Hashtable AuthorizationConfiguration = new();
        List<string> strings = new();

        string configFile = Path.Combine(BasicsPath, "json", "authorizationDocuments.json");
        // 查找配置文件
        if (File.Exists(configFile))
        {
            string str = File.ReadAllText(configFile);
            AuthorizationConfiguration = JsonSerializer.Deserialize<Hashtable>(str);
            foreach (var item in AuthorizationConfiguration.Keys)
            {
                strings.Add(item.ToString());
            }
        }
        return strings;
    }

    /// <summary>
    /// 获取分组名称
    /// </summary>
    /// <returns></returns>
    public static List<string> GetGroupName()
    {
        return GroupingData().Grouping;
    }

    /// <summary>
    /// 获取已授权列表
    /// </summary>
    /// <returns></returns>
    public static SortedList<string, List<string>> GetAuthorizedList()
    {
        SortedList<string, List<string>> returnValue = new();

        Hashtable AuthorizationConfiguration = new();

        string configFile = Path.Combine(BasicsPath, "json", "authorizationDocuments.json");
        // 查找配置文件
        if (File.Exists(configFile))
        {
            string str = File.ReadAllText(configFile);

            AuthorizationConfiguration = JsonSerializer.Deserialize<Hashtable>(str);

            foreach (var item in AuthorizationConfiguration.Keys)
            {
                try
                {
                    var equipmentList = JsonSerializer.Deserialize<List<string>>(AuthorizationConfiguration[item.ToString()].ToString());
                    returnValue.Add(item.ToString(), equipmentList);
                }
                catch (Exception)
                {
                }
            }
        }

        return returnValue;
    }


    /// <summary>
    /// 修改设备添加分组
    /// </summary>
    /// <returns></returns>
    public static string ModifyDevicesAndAddGroups(EquipmentGroupingSettingsModel settingsModel)
    {
        string configFile = Path.Combine(BasicsPath, "json", "authorizationDocuments.json");

        SortedList<string, List<string>> AuthorizationConfiguration = new();
        // 查找配置文件
        if (File.Exists(configFile))
        {
            string str = File.ReadAllText(configFile);

            AuthorizationConfiguration = JsonSerializer.Deserialize<SortedList<string, List<string>>>(str);

            if (settingsModel.Operations == Operation.Add)
            {
                if (AuthorizationConfiguration.ContainsKey(settingsModel.ClientId))
                {
                    if (AuthorizationConfiguration[settingsModel.ClientId].Contains(settingsModel.Grouping))
                    {
                        return "已添加分组，无需重复添加";
                    }
                    else
                    {
                        AuthorizationConfiguration[settingsModel.ClientId].Add(settingsModel.Grouping);
                    }
                }
                else
                {
                    AuthorizationConfiguration.Add(settingsModel.ClientId, new() { settingsModel.Grouping });
                }
            }
            else if (settingsModel.Operations == Operation.Delete)
            {
                if (AuthorizationConfiguration.ContainsKey(settingsModel.ClientId))
                {
                    if (AuthorizationConfiguration[settingsModel.ClientId].Contains(settingsModel.Grouping))
                    {
                        AuthorizationConfiguration[settingsModel.ClientId].Remove(settingsModel.Grouping);
                    }
                    else
                    {
                        return "分组不存在";
                    }
                }
                else
                {
                    return "分组不存在";
                }

            }
            else
            {
                return "操作指令错误";
            }
        }
        else
        {
            AuthorizationConfiguration.Add(settingsModel.ClientId, new() { settingsModel.Grouping });
        }
        File.WriteAllText(configFile, JsonSerializer.Serialize(AuthorizationConfiguration, new JsonSerializerOptions()
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        }));
        return "操作成功";
    }

    #region 获取系统Id
    /// <summary>
    /// 获取系统Id
    /// </summary>
    /// <returns></returns>
    //public static string GetSystemId()
    //{
    //    string systemId = null;
    //    using (ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_ComputerSystemProduct"))
    //    {
    //        foreach (var item in mos.Get())
    //        {
    //            systemId = item["UUID"].ToString()!;
    //        }
    //    }
    //    return systemId.Replace("-", "");
    //}
    #endregion
}

/// <summary>
/// 验证码
/// </summary>
public class Verification()
{
    public string Code { get; set; }

    public DateTime Time { get; set; }
}